/*
 * @Author: GuitarXiaohe && 2205227953@qq.com
 * @Date: 2024-01-13 18:33:00
 * @LastEditors: NaturalHulk 2066634567@qq.com
 * @LastEditTime: 2024-02-23 15:06:45
 * @FilePath: /umi/src/pages/system/user/index.jsx
 * @Description:
 * QQ:2205227953,邮箱:2205227953@qq.com
 * Copyright (c) 2024 by GuitarXiaohe, All Rights Reserved.
 */

import { Col, Card, Modal, Button, Form, Input, Select, TreeSelect, message, Row } from "antd";
import { FormOutlined, DeleteOutlined } from "@ant-design/icons";
import { Pagination } from "antd";
import { useEffect, useState, useRef } from "react";
import {
  XHbutton,
  XHmodal,
  XHtable,
  XHselectForm,
  XHoperate,
} from "@/components/xh-components/index";

import {
  GetListAPI,
  addUser,
  GetDeptDataAPI,
  getUser,
  delUser,
  updateUser,
} from "@/api/system/user";
import { connect } from "umi";
import { handleTree } from "@/utils/ruoyi";

const UserPage = (props) => {
  const { user, dispatch } = props;

  const { TextArea } = Input;

  // 列表枚举
  const columns = [
    { title: "用户编码", dataIndex: "userCode", align: "center" },
    { title: "用户姓名", dataIndex: "nickName", align: "center" },
    { title: "用户性别", dataIndex: "sex", align: "center" },
    { title: "部门", dataIndex: "deptName", align: "center" },
    { title: "角色", dataIndex: "roleStr", align: "center" },
    { title: "手机号", dataIndex: "phonenumber", align: "center" },
    { title: "邮箱", dataIndex: "email", align: "center" },
    { title: "状态", dataIndex: "status", align: "center" },
    { title: "备注", dataIndex: "remark", align: "center" },
    {
      title: "操作",
      width: 200,
      align: "center",
      render: (val) => (
        <>
          <XHoperate
            list={[
              {
                label: "修改",
                emit: () => editDic(val),
                permissions: "system:user:edit",
              },
              {
                label: "删除数据",
                danger: true,
                showMsg: true,
                emit: () => del(val),
                permissions: "system:user:remove",
              },
              {
                label: "查看",
                emit: () => see(val),
                permissions: "system:user:query",
              },
            ]}
          />
        </>
      ),
    },
  ];

  // 状态
  const [state, setState] = useState({
    loading: false,
    show: false,
    title: "新增",
    btnLoading: false,
    total: 0,
    keys: [],
    ids: [],
    list: [],
  });

  // 按钮枚举
  const [btnList, setBtnList] = useState();

  const selectForm = [
    {
      label: "时间",
      type: "时间日期",
    },
    {
      label: "姓名",
      model: "name",
      type: "输入框",
    },
  ];

  // 表单ref
  const formRef = useRef(null);

  //分页参数
  const [total, setTotal] = useState(0);

  //用户性别下拉数据
  const [sexArr, setSexArr] = useState([]);

  //部门下拉数据
  const [deptIdArr, setDeptIdArr] = useState([]);

  //角色下拉数据
  const [roleIdsArr, setRoleIdsArr] = useState([]);

  //表单数据
  const [dataForm, setdataForm] = useState({
    nickName: "", //用户姓名
    userName: "", //账号名称
    sex: "", //性别
    deptId: "", //部门
    roleIds: [], //角色
    phonenumber: "", //手机号
    email: "", //邮箱
    remark: "", //备注
  });

  const pageNum = useRef(1);
  const pageSize = useRef(10);

  // 列表参数
  const [query, setQuery] = useState({
    pageNum: 1,
    pageSize: 10,
  });

  // 列表数据
  const [tableData, setTableData] = useState({
    data: [],
    total: 0,
  });

  // 选择列表数据
  const [selTableData, setSelTableData] = useState({});

  const [value, setValue] = useState();
  const onChange = (newValue) => {
    setValue(newValue);
  };

  //使用Form.useForm创建表单数据域进行控制
  const [form] = Form.useForm();

  // 新增弹窗
  const addDic = () => {
    getUserList();
    getdeptTree();
    setState({
      ...state,
      show: true,
      title: "新增",
    });
  };

  // 修改弹窗
  const editDic = async (val) => {
    getdeptTree();
    try {
      dispatch({
        type: "appConfig/loading",
      });
      const res = await getUser(val.userId);
      const arr = res.roles.map((item) => ({
        value: item.roleId,
        label: item.roleName,
      }));
      setRoleIdsArr(arr);
      form.setFieldsValue({
        ...res.data,
        roleIds: res.roleIds,
      });
      setState({
        ...state,
        show: true,
        title: "修改",
      });
    } catch (err) {
      console.log(err);
    } finally {
      dispatch({
        type: "appConfig/closeLoading",
      });
    }
  };

  //查看弹窗
  const see = async (val) => {
    getdeptTree();
    try {
      dispatch({
        type: "appConfig/loading",
      });
      const res = await getUser(val.userId);
      const arr = res.roles.map((item) => ({
        value: item.roleId,
        label: item.roleName,
      }));
      setRoleIdsArr(arr);
      form.setFieldsValue({
        ...res.data,
        roleIds: res.roleIds,
      });
      setState({
        ...state,
        show: true,
        title: "查看",
      });
    } catch (err) {
      console.log(err);
    } finally {
      dispatch({
        type: "appConfig/closeLoading",
      });
    }
  };

  //新增保存
  const addSub = async () => {
    try {
      const result = await formRef.current.validateFields();
      if (!result) return;
      setState({
        ...state,
        btnLoading: true,
      });
      await addUser(result);
      message.success("新增成功!");
      handleCancel();
      getList();
    } catch (err) {
      console.log(err);
    } finally {
      setState({
        ...state,
        btnLoading: false,
      });
    }
  };

  //修改保存
  const editSub = async () => {
    try {
      const result = await formRef.current.validateFields();
      if (!result) return;
      setState({
        ...state,
        btnLoading: true,
      });
      await updateUser(result);
      message.success("修改成功!");
      handleCancel();
      getList();
    } catch (err) {
      console.log(err);
    } finally {
      setState({
        ...state,
        btnLoading: false,
      });
    }
  };

  //删除
  const del = async (val) => {
    dispatch({
      type: "appConfig/loading",
    });
    try {
      await delUser(val ? val.userId : state.ids);
      message.success("删除成功!");
      getList();
    } catch (err) {
      console.log(err);
    } finally {
      dispatch({
        type: "appConfig/closeLoading",
      });
    }
  };

  //弹窗xx关闭
  const handleCancel = () => {
    setState({
      ...state,
      show: false,
    });
    form.resetFields();
    form.setFieldsValue({
      nickName: "", //用户姓名
      userName: "", //账号名称
      sex: "", //性别
      deptId: "", //部门
      roleIds: [], //角色
      phonenumber: "", //手机号
      email: "", //邮箱
      remark: "", //备注
    });
  };

  //获取部门下拉数据
  const getdeptTree = async () => {
    const res = await GetDeptDataAPI({ type: 1 });
    const arr = handleTree(res.data, "deptId");
    setDeptIdArr(arr);
  };

  //获取角色下拉
  const getUserList = async (id) => {
    const res = await getUser(id ? id : "");
    const arr = res.roles.map((item) => ({
      value: item.roleId,
      label: item.roleName,
    }));
    setRoleIdsArr(arr);
  };

  // 查询条件
  const selectSubmit = (obj) => {
    setQuery({ ...query, ...obj });
    getList({ ...query, ...obj });
  };

  // 选择列表时变化
  const selChange = ({ keys, ids, list }) => {
    setState({ ...state, keys, ids, list });
  };

  // 获取列表
  const getList = async (v) => {
    try {
      setState({
        ...state,
        loading: true,
      });
      const result = await GetListAPI(v);
      setTableData({
        data: result.rows,
        total: result.total,
      });
    } catch (err) {
    } finally {
      setState({
        ...state,
        loading: false,
      });
    }
  };

  useEffect(() => {}, []);

  return (
    <>
      <Card>
        <XHselectForm list={selectForm} selectSubmit={selectSubmit} />
        <XHbutton
          list={[
            { text: "新增", type: "新增", emit: () => addDic() },
            {
              text: "删除",
              type: "删除",
              danger: true,
              emit: () => del(),
              showMsg: true,
              disabled: state.ids.length < 1,
            },
          ]}
        />
        <XHtable
          keyId="userId"
          loading={state.loading}
          dataSource={tableData.data}
          total={tableData.total}
          columns={columns}
          onChange={selChange}
          pagination={(val) => {
            setQuery({ ...query, ...val });
            getList({ ...query, ...val });
          }}
        />
      </Card>
      <XHmodal
        loading={state.btnLoading}
        open={state.show}
        title={state.title}
        ok={() => (state.title == "新增" ? addSub() : editSub())}
        no={() => {
          handleCancel();
        }}
        body={
          <Form
            form={form}
            ref={formRef}
            //这是label的占比份数，span表示份
            layout="vertical"
            //这个是输入框的占比份数

            initialValues={dataForm}
          >
            <Row gutter={24}>
              <Col span={10}>
                <Form.Item
                  label="用户姓名"
                  name="nickName"
                  rules={[
                    {
                      required: true,
                      message: "请输入用户姓名",
                    },
                  ]}
                >
                  <Input placeholder="请输入用户姓名" disabled={state.title == "查看"} />
                </Form.Item>
              </Col>

              <Col span={10}>
                <Form.Item
                  label="账号名称"
                  name="userName"
                  rules={[
                    {
                      required: true,
                      message: "请输入账号名称",
                    },
                  ]}
                >
                  <Input placeholder="请输入账号名称" disabled={state.title == "查看"} />
                </Form.Item>
              </Col>

              <Col span={10}>
                <Form.Item label="用户性别" name="sex">
                  <Select
                    allowClear
                    style={{
                      width: "100%",
                    }}
                    disabled={state.title == "查看"}
                    placeholder="请选择用户性别"
                    options={[
                      { value: "0", label: "男" },
                      { value: "1", label: "女" },
                    ]}
                  />
                </Form.Item>
              </Col>

              <Col span={10}>
                <Form.Item
                  label="部门"
                  name="deptId"
                  rules={[
                    {
                      required: true,
                      message: "请选择部门",
                    },
                  ]}
                >
                  <TreeSelect
                    showSearch
                    disabled={state.title == "查看"}
                    treeDefaultExpandAll
                    style={{
                      width: "100%",
                    }}
                    value={value}
                    dropdownStyle={{
                      maxHeight: 400,
                      overflow: "auto",
                    }}
                    fieldNames={{ label: "deptName", value: "deptId", children: "children" }}
                    placeholder="请选择部门"
                    allowClear
                    onChange={onChange}
                    treeData={deptIdArr}
                  />
                </Form.Item>
              </Col>

              <Col span={10}>
                <Form.Item
                  label="角色"
                  name="roleIds"
                  rules={[
                    {
                      required: true,
                      message: "请选择角色",
                    },
                  ]}
                >
                  <Select
                    disabled={state.title == "查看"}
                    allowClear
                    mode="multiple"
                    style={{
                      width: "100%",
                    }}
                    placeholder="请选择角色"
                    options={roleIdsArr}
                  />
                </Form.Item>
              </Col>

              <Col span={10}>
                <Form.Item label="手机号" name="phonenumber">
                  <Input placeholder="请输入手机号" disabled={state.title == "查看"} />
                </Form.Item>
              </Col>

              <Col span={10}>
                <Form.Item label="邮箱" name="email">
                  <Input placeholder="请输入邮箱" disabled={state.title == "查看"} />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <Form.Item label="备注" name="remark">
                  <TextArea
                    rows={4}
                    placeholder="请输入"
                    maxLength={6}
                    disabled={state.title == "查看"}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        }
      ></XHmodal>
    </>
  );
};

export default connect((state) => ({ user: state.user }))(UserPage);
